﻿using MediatR;
using System.Security.Cryptography;
using System.Xml.Linq;
using System;
using Traceability.App.Api.Read.DTO;
using Traceability.App.Domain.新文件夹;
using Traceability.App.ErrorCode;
using Traceability.App.Intrastructure.Interface;
using Traceability.App.Api.Read.Application.Command.Trace;

namespace Traceability.App.Api.Read.Application.Handler.Trace
{
    public class GetTraceaHandler : IRequestHandler<GetTraceaCommand, ApiPaging<TranceDTO>>
    {
        private readonly IBaseRepository<TraceabilityModel> traceaRepo;
        private readonly IBaseRepository<ShopModel> shopRepo;

        public GetTraceaHandler(IBaseRepository<TraceabilityModel> traceaRepo, IBaseRepository<ShopModel> shopRepo)
        {
            this.traceaRepo = traceaRepo;
            this.shopRepo = shopRepo;
        }
        public Task<ApiPaging<TranceDTO>> Handle(GetTraceaCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPaging<TranceDTO>();
            var tracea = traceaRepo.GetAll().Where(x => x.IsDel == false);
            var shop = shopRepo.GetAll().Where(x => x.IsDel == false);
            var linq = from a in tracea
                       join b in shop on a.Sid equals b.Id
                       select new TranceDTO
                       {
                           Id = a.Id,
                           Sid = a.Sid,
                           Sname = b.Sname,
                           ProduceBatch = a.ProduceBatch,
                           Shelflife = a.Shelflife,
                           ProduceNumber = a.ProduceNumber,
                           Manufacturers = a.Manufacturers,
                           DegreeinFormation = a.DegreeinFormation,
                           Img = a.Img,
                           CreatePeople = a.CreatePeople,
                           CreateTime = a.CreateTime,
                           UpdatePeople = a.UpdatePeople,
                           UpdateTime = a.UpdateTime,

                       };

            var totalcount = tracea.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            linq = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.totalcount = totalcount;
            res.totalpage = totalpage;
            res.Message = "显示成功";
            res.Code = ApiEnum.Ok;
            res.Data = linq.ToList();
            return Task.FromResult(res);
        }
    }
}
